# services/group_relationship_service.py
from typing import List

from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession

from common.util import singleton
from modules.mod import GroupRelationship
from service.GroupDBService import GroupDBService
from service.UserService import UserService

@singleton
class GroupRelationshipService:
    def __init__(
        self,
        user_service: UserService = UserService(),
        group_db_service: GroupDBService = GroupDBService()
    ):
        self.user_service = user_service
        self.group_db_service = group_db_service

    async def create_group_relationship(self, db: AsyncSession, data: dict) -> GroupRelationship:
        """
        添加群组关系（用户 - 群组绑定）
        """
        user_id = data.get("user_id")
        group_id = data.get("group_id")

        # 检查用户和群组是否存在
        if not await self.user_service.check_user_existence({ "user_id" : user_id}):
            raise ValueError(f"无效用户 ID: {user_id}")
        # if not await self.group_db_service.check_group_exists({"group_id": group_id}):
        #     raise ValueError(f"无效群组 ID: {group_id}")

        data = GroupRelationship(**data)
        db.add(data)
        await db.commit()
        return data

    async def get_group_relationships(self, db: AsyncSession, filters: dict) -> List[GroupRelationship]:
        """
        根据指定条件获取群组关系
        """
        repo = await db.execute(select(GroupRelationship).filter_by(**filters))
        return repo.scalars().all()